package com.pagoamigo.web;

import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.pagoamigo.domain.Account;
import com.pagoamigo.domain.Payment;

@RequestMapping("/mypayments/**")
@Controller
public class MyPaymentsController {

    @RequestMapping(method = RequestMethod.POST, value = "{id}")
    public void post(@PathVariable Long id, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
    }

    @RequestMapping
    public String list(Model uiModel, Principal principal) {
    	uiModel.addAttribute("usuario_logeado",principal.getName());
    	if (principal.getName()!=null || !principal.getName().isEmpty()){
    		List<Account> acc = Account.findAccountsByUsernameEquals(principal.getName()).getResultList();
    		if (!acc.isEmpty()){
    			List<Payment> receivedPayments = Payment.
						findPaymentsByReceiver(acc.get(0)).getResultList();
				uiModel.addAttribute("received_payments",receivedPayments);
				List<Payment> sentPayments = Payment.
						findPaymentsBySender(acc.get(0)).getResultList();
				uiModel.addAttribute("sent_payments",sentPayments);
    		}
    	}
        return "mypayments/list";
    }
    
    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Payment payment, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest, Principal principal) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, payment, principal.getName());
            return "mypayments/create";
        }
        uiModel.asMap().clear();
        payment.persist();
        return "redirect:/mypayments/" + encodeUrlPathSegment(payment.getId().toString(), httpServletRequest);
    }
    
    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel, Principal principal) {
        populateEditForm(uiModel, new Payment(), principal.getName());
        return "mypayments/create";
    }
    
    void populateEditForm(Model uiModel, Payment payment, String userName) {
        uiModel.addAttribute("payment", payment);
        uiModel.addAttribute("sender_account", Account.findAccountsByUsernameEquals(userName).getResultList());
        uiModel.addAttribute("accounts", Account.findAccountsByUsernameNotEquals(userName).getResultList());
    }
    
    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }
}
